home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 4678 < prev    next >
Encoding:
Internet Message Format  |  1996-08-06  |  1.9 KB

  1. Path: atglab.bls.com!Alun.Champion
  2. From: Alun.Champion@bridge.bst.bls.com (Alun Champion)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Interpreting whitespace w. cin
  5. Date: 31 Jan 1996 17:18:32 GMT
  6. Organization: Computer People Inc.
  7. Message-ID: <ALUN.CHAMPION.96Jan31121833@g7240065.bridge.bst.bls.com>
  8. References: <4emb7p$u0@guitar.hal.com>
  9. NNTP-Posting-Host: bstfirewall.bst.bls.com
  10. In-reply-to: blair@hal.COM's message of 30 Jan 1996 15:56:41 -0800
  11.  
  12. In article <4emb7p$u0@guitar.hal.com> blair@hal.COM (Blair Martin) writes:
  13.  
  14. : I want to write a program that uses new and delete to dynamically
  15. : allocate exactly enough free memory to hold string input data.
  16.  
  17. : That is, instead of allocating a fixed array of
  18. : characters from the stack, receive one character at a time and
  19. : continually allocate, copy, and release space so that the physical
  20. : and logical lengths of the buffer area are always the same.
  21. : When the newline character is encountered, print the string
  22. : and release the space. Then prompt for the next string. When
  23. : EOF is entered, terminate the program.
  24.  
  25.  
  26. : The problem is with a loop like
  27.  
  28. :     while (!(cin >> input).eof())
  29. :     {
  30. :           ...
  31. :     }
  32.  
  33. : there is no way to know when a newline is encountered since
  34. : all whitespace is ignored.
  35.  
  36. : Is there another way to do this?
  37.  
  38. As I understand this you are wanting to read the whole line of
  39. unspecified length into a string. Print it out - forget about it and
  40. continue to the next line.
  41.  
  42.   char ch;
  43.   ostrstream ostr;
  44.   while (cin >> ch)
  45.   {
  46.       ostr << ch;
  47.  
  48.       if (ch == '\n') {
  49.           ostr << ends;
  50.           cout << ostr.str();
  51.           ostr.rbbuf->freeze(0);
  52.           ostr.seekp(0);
  53.       }
  54.   }
  55.  
  56. The only problem with this is you cannot guarentee the exact length of allocated
  57. memory for the string (ostr.str()) because it is managed by the ostrstream,
  58. it does the necessary allocating and reallocating of memory.
  59. Otherwise it does exactly what you want.
  60.  
  61. Regards
  62.  
  63.   -A.
  64. -- 
  65. | A.Champion                |
  66.